package com.example.demo.controller;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Wrapper;


@RestController//用来访问json数据
@RequestMapping("/user")//定义统一路由
public class UserController {
    @Resource
    UserMapper userMapper;

    @PostMapping("/login")//登录逻辑
    public Result<?> login(@RequestBody User user){
        //获取匹配的密码和用户名，如果不匹配则输出错误信息
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()).eq(User::getPassword, user.getPassword()));
//        System.out.println(user.getUsername());
//        System.out.println( user.getPassword());
        if(res == null){
            return Result.error("-1","用户名或密码错误");
        }
        return Result.success();
    }

    @PostMapping("/register")//注册逻辑
    public Result<?> register(@RequestBody User user){

        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
//        System.out.println(user.getUsername());
//        System.out.println( user.getPassword());

        if(user.getPassword() == null){
            user.setPassword("123456");
        }
        if(res != null){
            return Result.error("-1","用户名重复");
        }

        userMapper.insert(user);
        return Result.success();
    }

    @PostMapping//post新增
    public Result<?> save(@RequestBody User user){
        if(user.getPassword() == null){
            user.setPassword("123456");
        }
        //insert已经封装好了不用知道细节
        userMapper.insert(user);
        return Result.success();
    }
    @DeleteMapping("/{id}")//删除
    public Result<?> save(@PathVariable Long id){

        userMapper.deleteById(id);
        return Result.success();
    }

    @PutMapping//更新
    public Result<?> update(@RequestBody User user){


        userMapper.updateById(user);
        return Result.success();
    }
    @GetMapping//查询
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,//defaultValue设置默认页数
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<User> wrapper = Wrappers.<User>lambdaQuery().like(User::getUsername, search);

        if(StrUtil.isNotBlank(search)){
            wrapper.like(User::getUsername,search);
        }
        Page<User> userPage = userMapper.selectPage(new Page<>(pageNum,pageSize),wrapper);
        return Result.success(userPage);
    }
}
